﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace VersionStar.App
{
    public class Program
    {
        public static int Main(string[] args)
        {
            try
            {
                Logger.Log("VersionStar");
                if (!args.Any())
                {
                    throw new InvalidOperationException("You must specify server name");
                }

                if (args.Count() < 2)
                {
                    throw new InvalidOperationException("You must specify database name");
                }

                DatabasePatcher patcher = new DatabasePatcher(serverName: args[0], databaseName: args[1], parameters: CreateParameters(args));
                patcher.Initialize();
                patcher.ApplyPatches();
                Logger.Log("Done!");

                if (args.Contains("pause"))
                {
                    Logger.Log("Press any key to continue");
                    Console.ReadKey();
                }

                return 0;
            }
            catch (Exception e)
            {
                Logger.Err("An error occured:");
                Logger.Err("*****************");
                Logger.Err(e.ToString());

                if (args.Contains("pause"))
                {
                    Console.WriteLine("Press any key to continue");
                    Console.ReadKey();
                }

                return -1;
            }
        }

        private static Dictionary<string, string> CreateParameters(string[] args)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var arg in args)
            {
                string[] keyValue = arg.Split('=');
                string key = keyValue[0];
                string value = keyValue.Count() > 1 ? keyValue[1].Trim() : null;
                dict.Add(key.Trim(), value);
            }
            return dict;
        }
    }
}
